package com.liang.wx.handler;

import com.liang.wx.enums.MessageTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 文本消息处理器
 */
@Slf4j
@Component
public class TextMessageHandler implements MessageHandler {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String KEY_WORD = "验证码";
    private static final String LOGIN_PREFIX = "login:";

    @Override
    public MessageTypeEnum getMessageType() {
        return MessageTypeEnum.TEXT;
    }

    @Override
    public String handle(Map<String, String> messageMap) {
        log.info("接收到文本消息事件");
        String content = messageMap.get("Content");
        if (!KEY_WORD.equals(content)) {
            return "";
        }
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");

        Random random = new Random();
        int code = random.nextInt(1000);
        String key = LOGIN_PREFIX + code;
        redisTemplate.opsForValue().setIfAbsent(key, fromUserName, 5L, TimeUnit.MINUTES);
        String numContent = "您当前的验证码是：" + code + "！ 5分钟内有效。";
        return "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
    }
}
